import numpy as np
import matplotlib.pyplot as plt
import struct
from scipy.signal import butter,lfilter,freqz

# y(n) = x(n) - x(n-N) + y(n-1)

# [0,0,0,0,0]   ptr = 0
# [1,0,0,0,0]   ptr = 1
# [1,2,0,0,0]   ptr = 2
# [1,2,3,0,0]   ptr = 3
# [1,2,3,4,0]   ptr = 4
# [1,2,3,4,5]   ptr = 0
# [6,2,3,4,5]   ptr = 1
# [6,7,3,4,5]   ptr = 2


class NavgFilter:
    def __init__ (self,Navg): #平滑滤波器，输入N实现N阶的平滑
        self.Navg = Navg
        self.xbuf = [0]*self.Navg #存储x(n-N)...x(n-1)
        self.ptr = 0 #指向最新的数据存放位置，x(n)
        self.yn = 0#存储y(n)

    def filter(self,xn):
        # n = self.ptr - self.Navg
        # if n < 0:
        #     n = n + self.Navg
        self.yn = self.yn + xn - self.xbuf[self.ptr]
        self.xbuf[self.ptr] = xn
        self.ptr = self.ptr+1
        if self.ptr == self.Navg:
            self.ptr = 0
        return self.yn/self.Navg


if __name__ =='__main__':

    fp = open("D:/wuhui/testcode/SmartHealth-master1/DATA/mitdb/102.dat","rb")
    fp_out = open("D:/wuhui/testcode/SmartHealth-master1/DATA/mitdb/102_out.dat","wb")
    diff = NavgFilter(5)
    for i in range(0, 250):
        x = struct.unpack('h',fp.read(2))
        y = diff.filter(x[0])
        fp_out.write(struct.pack('h',int(y)))
    fp.close()
    fp_out.close()
    ecg0 = np.fromfile("D:/wuhui/testcode/SmartHealth-master1/DATA/mitdb/102.dat",dtype=np.short)#按照short读取数据
    ecg1 = np.fromfile("D:/wuhui/testcode/SmartHealth-master1/DATA/mitdb/102_out.dat",dtype=np.short)
   
    # yn = yn1 + xn -x(n-5)
    ecg2 = lfilter( [1/5,0,0,0,0,-1/5], [1,-1], ecg0)#可以用于在线数据的滤波
    ecg3 = lfilter( [1/5,1/5,1/5,1/5,1/5], [1], ecg0)#使用 IIR 或 FIR 滤波器沿 one-dimension 过滤数据。使用数字滤波器过滤数据序列x

    
    plt.subplot(2,1,1)
    plt.plot(ecg0[0:250])
    plt.subplot(2,1,2)
    plt.plot(ecg1[0:250])
    plt.plot(ecg2[0:250])
    plt.plot(ecg3[0:250])
    plt.show()